import logging
from PySide6.QtWidgets import QWidget, QFileDialog
from docu_kit.ui.window_02_ui import Ui_Form
from docu_kit.runs.window_02_run import Window_Run
from docu_kit.windows.qtools import QTextBrowserHandler, QWorkThread


class Window(QWidget):
    """自定义Qt主窗口"""

    def __init__(self, logger=None):
        """初始化"""
        QWidget.__init__(self)
        formatter = logging.Formatter("%(asctime)s - %(levelname)s: %(message)s")  # 设置日志格式
        if logger:
            self.logger = logger
        else:
            # 设置日志
            self.logger = logging.getLogger("qt")  # 创建日志
            self.logger.setLevel(logging.DEBUG)  # 设置日志等级
            # 添加控制台处理器
            console_handler = logging.StreamHandler()
            console_handler.setLevel(logging.DEBUG)
            console_handler.setFormatter(formatter)
            self.logger.addHandler(console_handler)
        # 添加qt处理器
        qt_handler = QTextBrowserHandler()
        qt_handler.setLevel(logging.INFO)
        qt_handler.setFormatter(formatter)
        self.logger.addHandler(qt_handler)
        # 定义执行函数
        self.run = Window_Run(self.logger)
        # 初始化界面
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        # 定义执行线程
        self.thread = QWorkThread(self)
        # 事件绑定
        qt_handler.signal.connect(self.ui.textBrowser.append)
        self.ui.folderSearchButton.clicked.connect(self.search_folder)
        self.ui.runButton.clicked.connect(self.start)

    def search_folder(self):
        """选择文件夹"""
        folder_path = QFileDialog.getExistingDirectory(self, "选择文件夹")
        if folder_path:
            self.ui.folderPathLineEdit.setText(folder_path)

    def start(self):
        """开始运行"""
        folder_path = self.ui.folderPathLineEdit.text()
        if not folder_path:
            self.logger.error("请选择文件夹")
            return
        self.thread.set_run(lambda: self.run.batch_generate_file(folder_path))
        self.thread.start()  # 线程启动，执行run函数
